-- uu.lua
local uuhdr_ext=Proto.new("uuhdr_ext", "uuext header")

local uuhdr_ext_type_list = 
{
    [0x01] = "cell mr",
    [0x02] = "ue mr",
    [0x03] = "enodeb"
}

local uuhdr_ext_len = ProtoField.uint8("uuhdr_ext.len", "len", base.DEC)
local uuhdr_ext_type = ProtoField.uint8("uuhdr_ext.type", "type", base.HEX, uuhdr_ext_type_list)
local uuhdr_ext_enbid = ProtoField.uint32("uuhdr_ext.enodeb_id", "enodeb_id", base.DEC)
local uuhdr_ext_sectorid = ProtoField.uint16("uuhdr_ext.sectorid", "sectorid", base.DEC)
local uuhdr_ext_crnti= ProtoField.uint16("uuhdr_ext.c-rnti", "c-rnti", base.DEC)
local uuhdr_ext_mmeueid= ProtoField.uint32("uuhdr_ext.mme_ue_s1ap_id", "mme_ue_s1ap_id", base.DEC)
local uuhdr_ext_mmegid= ProtoField.uint16("uuhdr_ext.mme_groupid", "mme_groupid", base.DEC)
local uuhdr_ext_mmecode= ProtoField.uint8("uuhdr_ext.mme_code", "mme_code", base.DEC)
local uuhdr_ext_reverse = ProtoField.string("uuhdr_ext.reverse", "reverse")
local uuhdr_ext_data = ProtoField.string("uuhdr_ext.payload", "payload")

uuhdr_ext.fields = {uuhdr_ext_len, uuhdr_ext_type,  uuhdr_ext_enbid,
    uuhdr_ext_sectorid, uuhdr_ext_crnti, uuhdr_ext_mmeueid,
    uuhdr_ext_mmegid, uuhdr_ext_mmecode, uuhdr_ext_reverse, uuhdr_ext_data}

function uuhdr_ext.dissector(buf, pinfo, tree)
    pinfo.cols.protocol:set("Ue/Cell MR")
    local total_len = buf:len()
    local offset = 0
    -- 取得专用头长度
    local len = buf(offset, 1):uint()
    -- 建立uuhdr_ext_tree
    uuhdr_ext_tree = tree:add(uuhdr_ext, buf(offset, len + 1), "uuhdr_ext tree")

    -- hdrlen
    uuhdr_ext_tree:add(uuhdr_ext_len, buf(offset, 1))

    offset = offset + 1
    local left = len  

    -- ext type
    local ext_type = buf(offset, 1):uint()
    uuhdr_ext_tree:add(uuhdr_ext_type, buf(offset, 1))
    offset = offset + 1 
    left = left - 1

    -- enodeb id
    uuhdr_ext_tree:add(uuhdr_ext_enbid, buf(offset, 4))
    offset = offset + 4
    left = left - 4

    -- sector id
    uuhdr_ext_tree:add(uuhdr_ext_sectorid, buf(offset, 2))
    offset = offset + 2
    left = left - 2

    if (ext_type == 2) then
        -- crnti 
        uuhdr_ext_tree:add(uuhdr_ext_crnti, buf(offset, 2))
        offset = offset + 2
        left = left - 2

        -- mme_ue_s1ap_id
        uuhdr_ext_tree:add(uuhdr_ext_mmeueid, buf(offset, 4))
        offset = offset + 4
        left = left - 4

        -- mmegid 
        uuhdr_ext_tree:add(uuhdr_ext_mmegid, buf(offset, 2))
        offset = offset + 2
        left = left - 2

        -- mmecode
        uuhdr_ext_tree:add(uuhdr_ext_mmecode, buf(offset, 1))
        offset = offset + 1
        left = left - 1
    end

    -- reverse
    uuhdr_ext_tree:add(uuhdr_ext_reverse, buf(offset, left), left.." bytes")
    offset = offset + left

    local payloadlen = buf:len() - len - 1
    uuhdr_ext_tree:add(uuhdr_ext_data, buf(offset, payloadlen), payloadlen.." bytes")

end 
